package felix.things.router.mqtt.server.store.message;

import cn.hutool.core.util.StrUtil;
import felix.things.router.mqtt.server.common.message.IRetainMessageStoreService;
import felix.things.router.mqtt.server.common.message.RetainMessageStore;
import felix.things.router.mqtt.server.store.cache.RetainMessageCache;
import felix.things.router.mqtt.server.store.utils.TopicUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Felix
 * @date 2019/8/21
 */
@Service
public class RetainMessageStoreServiceImpl implements IRetainMessageStoreService {

    @Resource
    private RetainMessageCache retainMessageCache;

    @Override
    public void put(String topic, RetainMessageStore retainMessageStore) {
        retainMessageCache.put(topic, retainMessageStore);
    }

    @Override
    public RetainMessageStore get(String topic) {
        return retainMessageCache.get(topic);
    }

    @Override
    public void remove(String topic) {
        retainMessageCache.remove(topic);
    }

    @Override
    public boolean containsKey(String topic) {
        return retainMessageCache.containsKey(topic);
    }

    @Override
    public List<RetainMessageStore> search(String topicFilter) {
        List<RetainMessageStore> retainMessageStores = new ArrayList<RetainMessageStore>();
        if (!StrUtil.contains(topicFilter, '#') && !StrUtil.contains(topicFilter, '+')) {
            if (retainMessageCache.containsKey(topicFilter)) {
                retainMessageStores.add(retainMessageCache.get(topicFilter));
            }
        } else {
            retainMessageCache.all().forEach((topic, val) -> {
                if (StrUtil.split(topic, '/').size() >= StrUtil.split(topicFilter, '/').size()) {
                    String newTopicFilter = TopicUtils.topicConvert(topic, topicFilter);
                    if (topicFilter.equals(newTopicFilter)) {
                        retainMessageStores.add(val);
                    }
                }
            });
        }
        return retainMessageStores;
    }
}
